from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select
import time
from util.basedir import basedir


class Base():

    def __init__(self,driver):
        self.driver = driver

    def openurl(self, url):
        self.driver.get(url)

    # loc = (By.ID, "")
    def loc_ele(self, loc):
        return self.driver.find_element(*loc)

    # 定位一组元素
    def loc_eles(self, loc):
        return self.driver.find_elements(*loc)

    # 截屏的方法
    def capturepic(self, filename):
        t = time.strftime("%Y%m%d%H%M%S", time.localtime())
        self.driver.save_screenshot(basedir+"/data/"+t+filename)


    # 定义一个显示等待定位元素
    def loc_wait_ele(self, loc):
        return WebDriverWait(self.driver, 15, 1).until(EC.element_to_be_clickable(loc))

    # 定义一个鼠标方法，悬停  loc = (By.ID, "")
    def hoverele(self, loc):
        ele = self.loc_ele(loc)
        ActionChains(self.driver).move_to_element(ele).perform()
    # 双击
    def doubleclick(self, loc):
        ele = self.loc_ele(loc)
        ActionChains(self.driver).double_click(ele).perform()

    # 右击
    def rightclick(self, loc):
        ele = self.loc_ele(loc)
        ActionChains(self.driver).context_click(ele).click()

    # 键盘事件-回车
    def enter(self,loc):
        ele = self.loc_ele(loc)
        ele.send_keys(Keys.ENTER)

    # 键盘事件-全选
    def selectall(self, loc):
        ele = self.loc_ele(loc)
        ele.send_keys(Keys.CONTROL, 'A')

    # 键盘事件-复制
    def copyall(self, loc):
        ele = self.loc_ele(loc)
        ele.send_keys(Keys.CONTROL, 'C')

    # 键盘事件-粘贴
    def paste(self, loc):
        ele = self.loc_ele(loc)
        ele.send_keys(Keys.CONTROL, 'V')

    # 切iframe
    def switchframe(self, loc):
        ele = self.loc_ele(loc)
        self.driver.switch_to.frame(ele)

    # 退出iframe
    def backiframe(self):
        self.driver.switch_to.default_content()

    # 切换窗口
    def switchwindow(self, n):
        self.driver.switch_to.window(self.driver.window_handles[n])

    # 弹框处理
    def alert_ensure(self):
        self.driver.switch_to.alert.accept()

    # 弹框处理
    def alert_dismiss(self):
        self.driver.switch_to.alert.dismiss()

    # 下拉框选择
    def selectitem(self, loc, index):
        # 这个是定位出来的select标签的元素
        ele = self.loc_ele(loc)
        Select(ele).select_by_index(index)